﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcWiki.Model;
using MvcWiki.Repository;
using MvcWiki.User;

namespace MvcWiki.Service
{
    public class WikiNamespaceService : IWikiNamespaceService
    {
        IWikiRepositoryFactory RepositoryFactory;
        IUnitOfWork UnitOfWork;
        IWikiUserProvider WikiUserProvider;

        public WikiNamespaceService(IWikiRepositoryFactory repositoryFactory, IUnitOfWork unitOfWork, IWikiUserProvider wikiUserProvider)
        {
            this.RepositoryFactory = repositoryFactory;
            this.UnitOfWork = unitOfWork;
            this.WikiUserProvider = wikiUserProvider;
        }

        public IList<WikiNamespace> GetAllWikiNamespaces()
        {
            if (!WikiUserProvider.CanIndexNamespaces())
            {
                throw new MvcWiki.Exceptions.AuthorizationException();
            }

            return RepositoryFactory.GetWikiNamespaceRepository().GetAllWikiNamespaces();
        }

        public WikiNamespace GetWikiNamespace(string wikiNamespaceName)
        {
            var wikiNamespace = RepositoryFactory.GetWikiNamespaceRepository().GetWikiNamespace(wikiNamespaceName);

            if (!WikiUserProvider.CanViewNamespace(wikiNamespace))
            {
                throw new MvcWiki.Exceptions.AuthorizationException();
            }

            return wikiNamespace;
        }

        public void CreateWikiNamespace(WikiNamespace wikiNamespace)
        {
            if (!WikiUserProvider.CanCreateNamespace())
            {
                throw new MvcWiki.Exceptions.AuthorizationException();
            }

            RepositoryFactory.GetWikiNamespaceRepository().SaveWikiNamespace(wikiNamespace);

            UnitOfWork.Commit();
        }

        public void SaveWikiNamespace(WikiNamespace wikiNamespace)
        {
            if (!WikiUserProvider.CanEditNamespace(wikiNamespace))
            {
                throw new MvcWiki.Exceptions.AuthorizationException();
            }

            RepositoryFactory.GetWikiNamespaceRepository().SaveWikiNamespace(wikiNamespace);

            UnitOfWork.Commit();
        }

        public void DeleteWikiNamespace(string wikiNamespaceName)
        {
            var wikiNamespaceRepository = RepositoryFactory.GetWikiNamespaceRepository();

            var wikiNamespace = wikiNamespaceRepository.GetWikiNamespace(wikiNamespaceName);

            if (!WikiUserProvider.CanDeleteNamespace(wikiNamespace))
            {
                throw new MvcWiki.Exceptions.AuthorizationException();
            }

            wikiNamespaceRepository.DeleteWikiNamespace(wikiNamespace);

            UnitOfWork.Commit();
        }
    }
}
